package com.cgtong.android.activity;

import android.app.Dialog;
import android.content.Intent;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.db.UserAccount;
import com.cgtong.android.http.ApiManager;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.BaseDialog;
import com.kingja.loadsir.callback.SuccessCallback;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

/*
 * 积分兑换
 */
public class MyExchangeActivity extends BaseTitleActivity {

    @BindView(R.id.tv_jf)
    TextView tv_jf;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_getmoney)
    TextView tv_getmoney;

    private UserAccount account;

    private static final int DECIMAL_DIGITS = 1;//小数的位数

    private double money;

    @Override
    protected String getContentTitle() {
        return getString(R.string.txt_exc_title);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_my_exchange;
    }

    @Override
    protected void loadDataByNet() {
        initData();
    }

    @Override
    protected void onDataReloadByNet(View v) {

    }

    public void initData() {
        account = App.getInstance().getCurrentAccount();
        if (account != null) {
//            tv_money.setText(account.getMoney() + "元");
            tv_jf.setText(account.getScore() + "分");
        }

        getredpacketpool();

        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
    }

    @OnClick({R.id.title_left_txt, R.id.tv_getmoney, R.id.tv_exc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_txt:
                finish();
                break;
            case R.id.tv_getmoney:
                if (money >= 1) {
                    showGetMoneyDialog();
                } else {
                    ToastUtils.showShort(getString(R.string.txt_cannot_get_money));
                }
                break;
            case R.id.tv_exc:
                startActivity(new Intent(this, MyRecordsActivity.class));
                break;
            default:
                break;
        }
    }

    private void setEditLimit(final EditText editText) {
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                KeyboardUtils.showSoftInput(editText);
            }
        }, 400);
        InputFilter[] filters = {new EditInputFilter(200, DECIMAL_DIGITS)};
        editText.setFilters(filters);
    }


    private void showGetMoneyDialog() {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_edit_dialog2)
                .setViewListener(new BaseDialog.ViewListener() {
                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        final EditText content_txt = (EditText) view.findViewById(R.id.content_txt);
                        setEditLimit(content_txt);
                        // 点击确认
                        view.findViewById(R.id.confirm_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                String inputMoney = content_txt.getText().toString();
                                if (TextUtils.isEmpty(inputMoney)) {
                                    ToastUtils.showShort(getString(R.string.txt_hint_money));
                                    return;
                                }
                                double inputMoneyInt = Double.parseDouble(inputMoney);
                                if (inputMoneyInt > money) {
                                    ToastUtils.showShort(getString(R.string.txt_money_not_enough));
                                    return;
                                } else {
                                    getRedPacket(inputMoneyInt + "");
                                }
                                dialog.cancel();
                            }
                        });
                        view.findViewById(R.id.cancel_txt).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });
                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false)
                .setCancelOutSide(false)
                .setGravity(Gravity.CENTER)
                .setStyle(R.style.CenterDialogTheme)
                .show();
    }

    /**
     * 领取红包
     *
     * @param money
     */
    private void getRedPacket(String money) {
        EasyHttp.post(ApiManager.URL_GET_REDPACKET)
                .params("money", money)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                    }

                    @Override
                    public void onSuccess(String result) {
                        try {
                            JSONObject jsonObj = new JSONObject(result);
                            if (jsonObj.optInt("code") == 0) {
                                ToastUtils.showLong(getString(R.string.txt_tip_get_red_package));
                            } else {
                                ToastUtils.showShort(jsonObj.optString("msg"));
                            }
                            getredpacketpool();
                            KeyboardUtils.hideSoftInput(MyExchangeActivity.this);
                        } catch (Exception e) {
                            LogUtils.e(e.toString());
                        }
                    }
                });
    }

    /**
     * 获取红包钱数
     */
    private void getredpacketpool() {
        EasyHttp.post(ApiManager.URL_GET_GETREDPACKETPOOL)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                    }

                    @Override
                    public void onSuccess(String result) {
                        try {
                            JSONObject jsonObj = new JSONObject(result);
                            if (jsonObj.optInt("code") == ConstantManager.RESULT_SUCCESS) {
                                JSONObject dataObj = jsonObj.optJSONObject("data");
                                money = dataObj.optDouble("redpacketTotal");
                                tv_money.setText(money + "元");
                            } else {
                                ToastUtils.showShort(jsonObj.optString("msg"));
                            }
                        } catch (Exception e) {
                        }
                    }
                });
    }

    private class EditInputFilter implements InputFilter {
        /**
         * 最大数字
         */
        public double MAX_VALUE;
        /**
         * 小数点后的数字的位数
         */
        public int PONTINT_LENGTH;
        Pattern p;

        public EditInputFilter(double maxValue, int length) {
            this.MAX_VALUE = maxValue;
            this.PONTINT_LENGTH = length;
            p = Pattern.compile("[0-9]*");   //除数字外的其他的
        }

        /**
         * source    新输入的字符串
         * start    新输入的字符串起始下标，一般为0
         * end    新输入的字符串终点下标，一般为source长度-1
         * dest    输入之前文本框内容
         * dstart    原内容起始坐标，一般为0
         * dend    原内容终点坐标，一般为dest长度-1
         */

        @Override
        public CharSequence filter(CharSequence src, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            String oldtext = dest.toString();
            System.out.println(oldtext);
            //验证删除等按键
            if ("".equals(src.toString())) {
                return null;
            }
            //验证非数字或者小数点的情况
            Matcher m = p.matcher(src);
            if (oldtext.contains(".")) {
                //已经存在小数点的情况下，只能输入数字
                if (!m.matches()) {
                    return null;
                }
            } else {
                //未输入小数点的情况下，可以输入小数点和数字
                if (!m.matches() && !src.equals(".")) {
                    return null;
                }
            }
            //验证输入金额的大小
            if (!src.toString().equals("")) {
                double dold = Double.parseDouble(oldtext + src.toString());
                if (dold > MAX_VALUE) {
                    return dest.subSequence(dstart, dend);
                } else if (dold == MAX_VALUE) {
                    if (src.toString().equals(".")) {
                        return dest.subSequence(dstart, dend);
                    }
                }
            }
            //验证小数位精度是否正确
            if (oldtext.contains(".")) {
                int index = oldtext.indexOf(".");
                int len = dend - index;
                //小数位只能2位
                if (len > PONTINT_LENGTH) {
                    CharSequence newText = dest.subSequence(dstart, dend);
                    return newText;
                }
            }
            return dest.subSequence(dstart, dend) + src.toString();
        }
    }
}
